/**   
 * Copyright © 2020 Fan_繁. All rights reserved.
 * 
 * @Title: HandleThreadPoolUtil.java 
 * @Prject: DataExtraction
 * @Package: com.fanml.xyz 
 * @Description: TODO
 * @author: ChuanHui 
 * @date: 2020年9月17日 下午4:09:35 
 * @version: V1.0   
 */
package com.fanml.xyz;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

/**
 * @ClassName: HandleThreadPoolUtil
 * @Description: 线程工具类
 * @author: ChuanHui
 * @date: 2020年9月17日 下午4:09:35
 */
public class HandleThreadPoolUtil {

	private static HandleThreadPoolUtil instance;
	private ThreadPoolExecutor executor;

	private TimeUnit unit = TimeUnit.SECONDS;

	public HandleThreadPoolUtil() {
		LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(1024);
		int corePoolSize = 4;
		long keepAliveTime = 1;
		int maximumPoolSize = 32;
		final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("fanml-thread-%d").build();
		executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory,
				new ThreadPoolExecutor.AbortPolicy());
	}

	public static HandleThreadPoolUtil getInstance() {
		if (instance == null) {
			synchronized (HandleThreadPoolUtil.class) {
				if (instance == null) {
					instance = new HandleThreadPoolUtil();
				}
			}
		}
		return instance;
	}

	public void awaitTermination() throws InterruptedException {
		long timeout = 10;
		executor.awaitTermination(timeout, unit);
	}

	public void execute(Runnable t) {
		executor.execute(t);
	}

	public void execute(Thread t) {
		executor.execute(t);
	}

	public int getQueueSize() {
		return executor.getQueue().size();
	}

	public void shutdown() {
		getExecutor().shutdown();
	}

	private ThreadPoolExecutor getExecutor() {
		return executor;
	}

	public Future<?> submit(Runnable t) {
		return executor.submit(t);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Future<?> submit(Callable t) {
		return getExecutor().submit(t);
	}

}
